package com.zoe.onelink.logging.trace.http.interceptor;

import brave.Tracer;
import com.alibaba.fastjson.JSON;
import com.zoe.onelink.common.constant.TraceSpanConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * <p>标题: 由于旧版本存在大量application/json 没有使用@RequestBody的方式接收,所以暂时不使用该方式记录BODY请求参数</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-05-06
 */
// @RestControllerAdvice
@RequiredArgsConstructor
public class TraceRequestBodyAdvice implements RequestBodyAdvice, Ordered {

    private final Tracer tracer;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        String jsonBody = JSON.toJSONString(body);
        this.tracer.currentSpan().tag(TraceSpanConstant.HTTP_PARAM, jsonBody);
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        this.tracer.currentSpan().tag(TraceSpanConstant.HTTP_PARAM, "");
        return body;
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE - 1000;
    }
}
